﻿''' <summary>
''' Library of various useful functions.
''' </summary>
''' <remarks></remarks>
Public Class Utilities

    ''' <summary>
    ''' This function can be used to instantiate a single instance form. If form already exists, it is displayed,
    ''' otherwise it is first instantiated and then displayed.
    ''' </summary>
    ''' <param name="frm">A form object to be instantiated.</param>
    ''' <param name="MDIContainer">If form should be created as a child form of an MDI container, specify the MDI container using this parameter.
    ''' Set parameter to Nothing if an MDI child form is not required.</param>
    ''' <remarks>This function does not support passing parameters to the form constructor. 
    ''' Form must have a default parameter-less constructor available.</remarks>
    Public Shared Sub LoadSingleInstanceForm(ByRef frm As Form, ByRef MDIContainer As Form)
        Static LoadedForms As New Dictionary(Of System.Type, Form)

        Dim FormType = frm.GetType()


        Dim TargetForm As Form = Nothing

        If LoadedForms.ContainsKey(FormType) Then
            TargetForm = LoadedForms.Item(FormType)
            If TargetForm Is Nothing OrElse TargetForm.IsDisposed Then
                TargetForm = CType(FormType.GetConstructor(New Type() {}).Invoke(Nothing), Form)
                If MDIContainer IsNot Nothing AndAlso MDIContainer.IsMdiContainer Then TargetForm.MdiParent = MDIContainer
                LoadedForms.Item(FormType) = TargetForm
            End If
            If TargetForm.WindowState = FormWindowState.Minimized Then TargetForm.WindowState = FormWindowState.Normal
            TargetForm.Show()
            TargetForm.BringToFront()
        Else
            TargetForm = CType(FormType.GetConstructor(New Type() {}).Invoke(Nothing), Form)
            LoadedForms.Add(FormType, TargetForm)
            If MDIContainer IsNot Nothing AndAlso MDIContainer.IsMdiContainer Then TargetForm.MdiParent = MDIContainer
            TargetForm.Show()
            TargetForm.BringToFront()
        End If
    End Sub
End Class
